import { asyncRouterMap, constantRouterMap } from '@/config/router.config'
import { getMenuAll } from '@/api/menu'
import { UserLayout, BasicLayout, RouteView, BlankLayout, PageView } from '@/layouts'
import store from '@/store'
import { resetRouter } from '@/router'
import Vue from 'vue'
const constantRouterComponents = {
  // 基础页面 layout 必须引入
  BasicLayout: BasicLayout,
  BlankLayout: BlankLayout,
  RouteView: RouteView,
  PageView: PageView,

  // 你需要动态引入的页面组件
  // 工作台
  desktopIndex: () => import('@/views/desktop'),
  desktopArticleDetail: () => import('@/views/desktop/articleDetail'),

  // 系统管理
  menu: () => import('@/views/system/menu'),
  dictionary: () => import('@/views/system/dictionary'),
  department: () => import('@/views/system/department'),
  position: () => import('@/views/system/position'),
  area: () => import('@/views/system/area'),
  systemSign: () => import('@/views/system/sign'),
  deptman: () => import('@/views/system/deptman'),
  deptposition: () => import('@/views/system/deptposition'),
  userManage: () => import('@/views/userm/manage'),
  roleManage: () => import('@/views/userm/role'),
  permissionManage: () => import('@/views/userm/permission'),
  uReportManage: () => import('@/views/system/uReportManage'),
  dispose: () => import('@/views/system/dispose'),
  workday: () => import('@/views/system/workday'),

  // 系统日志
  systemLogs: () => import('@/views/system/systemLogs'),

  // 通知公告
  informSendMes: () => import('@/views/inform/sendMes'),
  informList: () => import('@/views/inform/list'),
  // 自定义报表
  reportFormsIndex: () => import('@/views/reportForms'),
  reportFormsDesign: () => import('@/views/reportForms/design'),
  reportFormsRender: () => import('@/views/reportForms/render'),
  // 供应商
  supplierInfo: () => import('@/views/supplier/info'),
  supplierEdit: () => import('@/views/supplier/edit'),
  supplierDetail: () => import('@/views/supplier/detail'),
  supplierDetailBasic: () => import('@/views/supplier/detail/basic'),
  supplierDetailFile: () => import('@/views/supplier/detail/file'),
  supplierDetailContract: () => import('@/views/supplier/detail/contract'),
  supplierAccess: () => import('@/views/supplier/access'),
  supplierContract: () => import('@/views/supplier/contact'),
  supplierBadrecord: () => import('@/views/supplier/badrecord'),
  // 固定资产
  assetsIndex: () => import('@/views/assetsNew/index'),
  assetsClassify: () => import('@/views/assetsNew/classify'),
  assetsInfo: () => import('@/views/assetsNew/info'),
  assetsInfoDetail: () => import('@/views/assetsNew/infoDetail'),
  assetsDetail: () => import('@/views/assetsNew/detail'),
  assetsCheck: () => import('@/views/assetsNew/checkManage'),
  assetsNewDetail: () => import('@/views/assetsNew/detail'),
  assetsPlan: () => import('@/views/assetsNew/plan'),
  assetsPlanDetail: () => import('@/views/assetsNew/planDetail'),
  assetsPlanCreate: () => import('@/views/assetsNew/planCreate'),
  assetsNewCheckAudit: () => import('@/views/assetsNew/planCheckAudit'),
  assetsNewCheckAuditDetail: () => import('@/views/assetsNew/planCheckAuditDetail'),
  accessEquipment: () => import('@/views/assetsNew/accessEquipment'),
  // 内部满意度
  satisfactionClassify: () => import('@/views/satisfaction/classify'),
  satisfactionDefine: () => import('@/views/satisfaction/define'),
  satisfactionLevel: () => import('@/views/satisfaction/level'),
  satisfactionScheme: () => import('@/views/satisfaction/scheme'),
  satisfactionSchemeDetail: () => import('@/views/satisfaction/schemeDetail'),
  satisfactionTask: () => import('@/views/satisfaction/task'),
  satisfactionTaskDetail: () => import('@/views/satisfaction/taskDetail'),
  satisfactionTaskDept: () => import('@/views/satisfaction/taskDept'),
  satisfactionTaskAll: () => import('@/views/satisfaction/taskAll'),
  satisfactionList: () => import('@/views/satisfaction/list'),
  satisfactionStartTest: () => import('@/views/satisfaction/startTest'),
  satisfactionCreateScheme: () => import('@/views/satisfaction/createScheme'),
  // 综合考评
  evaluateClassify: () => import('@/views/evaluate/classify'),
  evaluateDefine: () => import('@/views/evaluate/define'),
  evaluateProject: () => import('@/views/evaluate/project'),
  evaluateDeclare: () => import('@/views/evaluate/declare'),
  evaluateDeclareDeptP: () => import('@/views/evaluate/declareDeptP'),
  evaluateDeclareAllP: () => import('@/views/evaluate/declareAllP'),
  evaluateDeclareAll: () => import('@/views/evaluate/declareAll'),
  evaluateDeclareDept: () => import('@/views/evaluate/declareDept'),
  evaluateDeclareRecord: () => import('@/views/evaluate/declareRecord'),
  evaluateVerify: () => import('@/views/evaluate/verify'),
  evaluateVerify2: () => import('@/views/evaluate/verify2'),
  evaluateVerifyAll: () => import('@/views/evaluate/verifyAll'),
  evaluatePlanVerify: () => import('@/views/evaluate/planVerify'),
  evaluatePlanVerifyTable: () => import('@/views/evaluate/planVerifyTable'),
  evaluatePlan: () => import('@/views/evaluate/plan'),
  evaluateCreatePlan: () => import('@/views/evaluate/createPlan'),
  evaluatePlanDetail: () => import('@/views/evaluate/planDetail'),
  evaluateMyPlan: () => import('@/views/evaluate/myPlan'),
  evaluateMyPlanDept: () => import('@/views/evaluate/myPlanDept'),
  evaluateMyPlanAll: () => import('@/views/evaluate/myPlanAll'),
  evaluateStartTest: () => import('@/views/evaluate/startTest'),
  evaluateTable: () => import('@/views/evaluate/evaluateTable'),
  evaluateStartCreateTest: () => import('@/views/evaluate/startCreateTest'),
  evaluateDetail: () => import('@/views/evaluate/evaluateDetail'),
  evaluateAdditional: () => import('@/views/evaluate/evalAdditional'),
  evaluateFinishDetail: () => import('@/views/evaluate/finishDetail'),
  // 医德医风
  medicalPerson: () => import('@/views/medicalEthics/eval/person'),
  medicalOffice: () => import('@/views/medicalEthics/eval/office'),
  medicalBranch: () => import('@/views/medicalEthics/eval/branch'),
  medicalCommittee: () => import('@/views/medicalEthics/eval/committee'),
  medicalEthicsCreatePerson: () => import('@/views/medicalEthics/eval/createPerson'),
  moralityDefine: () => import('@/views/medicalEthics/define'),
  moralityCycle: () => import('@/views/medicalEthics/evalutionCycle'),
  moralityLevel: () => import('@/views/medicalEthics/basisVerb/level'),
  branchDept: () => import('@/views/medicalEthics/branchDept'),
  moralityComment: () => import('@/views/medicalEthics/basisVerb/commentTemplate'),
  moralityScheme: () => import('@/views/medicalEthics/scheme'),
  moralitySchemeDept: () => import('@/views/medicalEthics/schemeDept'),
  moralitySchemeAll: () => import('@/views/medicalEthics/schemeAll'),
  moralitySchemeDetail: () => import('@/views/medicalEthics/schemeDetail'),
  moralityCreateScheme: () => import('@/views/medicalEthics/createScheme'),
  // 患者满意度
  externalDefine: () => import('@/views/external/define'),
  externalDeptPlan: () => import('@/views/external/deptPlan'),
  externalType: () => import('@/views/external/type'),
  externalLevel: () => import('@/views/external/level'),
  externalRecord: () => import('@/views/external/record'),
  externalScheme: () => import('@/views/external/scheme'),
  externalSchemeDept: () => import('@/views/external/schemeDept'),
  externalSchemeAll: () => import('@/views/external/schemeAll'),
  externalCreateScheme: () => import('@/views/external/createScheme'),
  externalSchemeDetail: () => import('@/views/external/schemeDetail'),

  // 监控台
  monitorIndex: () => import('@/views/monitor'),
  partDetail: () => import('@/views/monitor/partDetail'),
  windowDetail: () => import('@/views/monitor/windowDetail'),
  prewarningDetail: () => import('@/views/monitor/prewarningDetail'),
  processDetail: () => import('@/views/monitor/processDetail'),
  monitorEvalDetail: () => import('@/views/monitor/evalDetail'),
  monitorEvalItemDetail: () => import('@/views/monitor/evalItemDetail'),
  monitorPersonDetail: () => import('@/views/monitor/personEvalDetail'),
  monitorPersonItemDetail: () => import('@/views/monitor/personItemDetail'),
  monitorTransDetail: () => import('@/views/monitor/transDetail'),
  monitorDoctorDetail: () => import('@/views/monitor/doctorDetail'),
  monitorPatientDetail: () => import('@/views/monitor/patientDetail'),
  monitorSupplierDetail: () => import('@/views/monitor/supplierDetail'),

  // 档案管理
  archivesUser: () => import('@/views/archives/userList'),
  archivesUserDetail: () => import('@/views/archives/userDetail'),
  archivesIntegrity: () => import('@/views/archives/integrityList'),
  archivesIntegrityDetail: () => import('@/views/archives/integrityDetail'),
  archivesCheck: () => import('@/views/archives/checkList'),

  // 报表
  reportsIndex: () => import('@/views/reports/index'),
  // report1: () => import('@/views/reports/report1'),
  report2: () => import('@/views/reports/report2'),
  report3: () => import('@/views/reports/report3'),
  report4: () => import('@/views/reports/report4'),
  report5: () => import('@/views/reports/report5'),
  report6: () => import('@/views/reports/report6'),
  report7: () => import('@/views/reports/report7'),
  report7Detail: () => import('@/views/reports/report7/handleDetail'),
  report8: () => import('@/views/reports/report8'),
  report9: () => import('@/views/reports/report9'),
  report10: () => import('@/views/reports/report10'),
  report11: () => import('@/views/reports/report11'),
  report11Detail: () => import('@/views/reports/report11/handleDetail'),
  report12: () => import('@/views/reports/report12'),
  report13: () => import('@/views/reports/report13'),
  report14: () => import('@/views/reports/report14'),
  report15: () => import('@/views/reports/report15'),
  report16: () => import('@/views/reports/report16'),
  report17: () => import('@/views/reports/report17'),
  report18: () => import('@/views/reports/report18'),
  report19: () => import('@/views/reports/report19'),

  // 预警
  prewarningRules: () => import('@/views/prewarning/rules'),
  prewarningHandle: () => import('@/views/prewarning/handle'),
  prewarningLog: () => import('@/views/prewarning/log'),

  // cms
  cmsColumn: () => import('@/views/CMS/column'),
  cmsArticle: () => import('@/views/CMS/article'),
  articleDetail: () => import('@/views/CMS/articleDetail'),

  // 流程
  /**BEGIN 工作流 */

  // 流程表单
  formList: () => import('@/views/workflow/form/index'),
  createForm: () => import('@/views/workflow/form/create'),
  updateForm: () => import('@/views/workflow/form/update'),
  designFormList: () => import('@/views/workflow/form/set'),
  designForm: () => import('@/views/workflow/generator/Home'),

  // 流程管理
  // 流程设计列表
  designBpmn: () => import('@/views/workflow/bpmn'),
  // 流程设计
  createBpmn: () => import('@/views/workflow/bpmn/create'),
  // 流程部署列表
  deployBpmn: () => import('@/views/workflow/bpmn/deploy'),
  // 我的任务
  bpmnTask: () => import('@/views/workflow/bpmn/task'),
  // 流程实例
  process: () => import('@/views/workflow/bpmn/process'),
  // 流程监控首页
  bpmnWatch: () => import('@/views/workflow/bpmn/watch'),
  // 流程监控按分类查看的列表
  bpmnWatchClassify: () => import('@/views/workflow/bpmn/watch/classify'),

  // 回溯列表
  backtrackSetList: () => import('@/views/workflow/backtrack/setList'),
  // 回溯设置
  backtrackSet: () => import('@/views/workflow/backtrack/set'),
  // 回溯查看页面
  backtrack: () => import('@/views/workflow/backtrack/index'),

  /**END 工作流 */

  person: () => import('@/views/person'),
}

/**
 * 过滤账户是否拥有某一个权限，并将菜单从加载列表移除
 *
 * @param permission
 * @param route
 * @returns {boolean}
 */
function hasPermission(permission, route) {
  if (route.meta && route.meta.permission) {
    let flag = false
    for (let i = 0, len = permission.length; i < len; i++) {
      flag = route.meta.permission.includes(permission[i])
      if (flag) {
        return true
      }
    }
    return false
  }
  return true
}

/**
 * 单账户多角色时，使用该方法可过滤角色不存在的菜单
 *
 * @param roles
 * @param route
 * @returns {*}
 */
// eslint-disable-next-line
function hasRole(roles, route) {
  if (route.meta && route.meta.roles) {
    return route.meta.roles.includes(roles.id)
  } else {
    return true
  }
}

function handleRouteData(arr, parent) {
  arr.map(v => {
    v.meta = Object.assign({}, JSON.parse(v.meta))
    v.hidden = v.meta.hidden
    v.component = !parent ? BasicLayout : constantRouterComponents[v.meta.component]
    if (v.children && v.children.length > 0) {
      v.redirect = v.children[0].path
      handleRouteData(v.children, v)
    } else {
      delete v.children
    }
  })
  return arr
}

function handleComponent(uri) {
  return require('@/views' + uri)
}

function filterAsyncRouter(routerMap, roles) {
  const accessedRouters = routerMap.filter(route => {
    if (hasPermission(roles.permissionList, route)) {
      if (route.children && route.children.length) {
        route.children = filterAsyncRouter(route.children, roles)
      }
      return true
    }
    return false
  })
  return accessedRouters
}

const permission = {
  state: {
    routers: constantRouterMap,
    addRouters: []
  },
  mutations: {
    SET_ROUTERS: (state, routers) => {
      state.addRouters = routers
      state.routers = constantRouterMap.concat(routers)
    }
  },
  actions: {
    GenerateRoutes({ commit }, data) {
      resetRouter()
      return new Promise(async resolve => {
        // console.log('GenerateRoutes==============');
        let userInfo = store.getters.userInfo
        userInfo = userInfo && Object.keys(userInfo).length ? userInfo : Vue.ls.get('userInfo')
        let positionRoutes = []
        if (userInfo && userInfo.deptId && userInfo.positionId) {
          const params = {
            deptId: userInfo.deptId,
            positionId: userInfo.positionId
          }
          const res = await getMenuAll(params)
          positionRoutes = res.data
        }
        // const res = await getMenuAll()
        const routes = handleRouteData(positionRoutes)
        const accessRouter = [...asyncRouterMap, ...routes]
        commit('SET_ROUTERS', accessRouter)

        resolve(accessRouter)
      })
    }
  }
}

export default permission
